package tt.dz.order.service.rpc.rpchander;

import java.util.List;

import org.apache.avro.generic.GenericRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;

import tt.dz.order.exception.BusinessException;
import tt.dz.order.service.OrderService;
import tt.dz.order.util.OrderConstant.BizSystemCode;
import tt.dz.order.vo.CreatedOrderVO;
import tt.dz.order.vo.OrderBaseData;
import tt.dz.order.vo.RetVO;

@Component("createOrderHander")
public class CreateOrderHander implements BaseHander {
	private static Logger log = LoggerFactory.getLogger(CreateOrderHander.class);
	@Autowired
	OrderService orderService;

	@Override
	public RetVO dohander(GenericRecord req) {
		RetVO retVO = new RetVO(RetVO.SuccessCode, null, null);
		// 下单
		try {
			String reqStr = req.get("orderBaseDatas").toString();
			log.info("下单reqStr：" + reqStr);
			List<OrderBaseData> orderBaseDatas = JSON.parseArray(reqStr, OrderBaseData.class);
			for (OrderBaseData baseData : orderBaseDatas) {
				baseData.validate();
				// 转移值，将订单中当前的电桩编号以及电站Id传递到分层数据结构之中
				if (baseData.getDivideInfo() != null) {
					baseData.getDivideInfo().setPlantId(baseData.getPlantId());
					baseData.getDivideInfo().setKeyLink(baseData.getEquipmentNo());
				}
			}
			CreatedOrderVO createdOrderVO = orderService.createOrder(orderBaseDatas);
			retVO.setBizData(createdOrderVO);
		} catch (JSONException e) {
			log.error("下单发生异常", e);
			retVO.setRetCode(RetVO.FailCode);
			retVO.setResultCode(new StringBuilder(BizSystemCode.OrderServer.value())
					.append(new BusinessException("").getExceptionCode()).append("00").toString());
			retVO.setErrorMsg(e.getMessage());
		} catch (BusinessException e) {
			log.error("下单发生异常", e);
			retVO.setRetCode(RetVO.FailCode);
			retVO.setResultCode(e.getExceptionCode());
			retVO.setErrorMsg(e.getMessage());
		} catch (Exception e) {
			log.error("下单发生异常", e);
			retVO.setRetCode(RetVO.FailCode);
			retVO.setResultCode("1020300");
			retVO.setErrorMsg(e.getMessage());
		}
		return retVO;
	}

}
